package com.gzsxy.excel.controller;

import com.gzsxy.excel.entity.FeedbackExportVo;
import com.gzsxy.excel.service.FeedbackService;
import com.gzsxy.excel.util.ExcelConsumer;
import com.gzsxy.excel.util.ExportDataAdapter;
import com.gzsxy.excel.util.ThreadPool;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

@RequestMapping("/FeedbackExcelExport")
@RestController
public class FeedbackExcelExport {
	
	public ThreadPoolExecutor executor = ThreadPool.getExecutor();

	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");

	@Autowired
	private FeedbackService feedbackService;
	 /**
     * 导出统计反馈查询信息
     * @param request
     * @param response
     */
	 @GetMapping("/FeedbackExport")
    @RequestMapping(value = "/FeedbackExport", method = { RequestMethod.GET, RequestMethod.POST})
    public void FeedbackExport(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");

        Map<String, Object> map = new HashMap<String, Object>();

        //导出excel对象
        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(1000);
        //数据缓冲
        ExportDataAdapter<FeedbackExportVo> exportDataAdapter = new ExportDataAdapter<>();
        //线程同步对象
        CountDownLatch latch = new CountDownLatch(2);

        //启动线程获取数据(生产者)
        executor.submit(()->{
            produceExportDataForTjcx(exportDataAdapter,latch, map);
        });
        //启动线程导出数据（消费者）
        executor.submit(()->{
            new ExcelConsumer<FeedbackExportVo>(FeedbackExportVo.class,exportDataAdapter,sxssfWorkbook,latch,"Sheet1").run();
        });

        String tempFile = System.getProperty("user.dir") + File.separator + "temp_" + DATE_FORMAT.format(new Date())+ ".xlsx";
        File file = new File(tempFile);
        FileOutputStream fos = null;
        OutputStream os = null;

        try {
            latch.await();
            System.out.println("全部执行完了");

            //导出准备
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("反馈信息_" + DATE_FORMAT.format(new Date()) + ".xlsx"));
            response.setContentType("application/os-stream;charset=UTF-8");

            fos = new FileOutputStream(file);
            //数据流写入到文件中去
            sxssfWorkbook.write(fos);
            fos.flush();
            fos.close();
            System.out.println("数据写入完成");

            os = response.getOutputStream();
            FileUtils.copyFile(file, os);

        } catch (Exception e) {
        	System.out.println("Excel数据导出失败，原因：" + e);
        } finally {
            try{
                if(fos!=null) {
                    fos.close();
                }

                if(file.exists()) {
                    FileUtils.forceDelete(file);
                }
                os.flush();    
                os.close();
            }catch(IOException ee){
                ee.printStackTrace();
            }

        }
    }

    //模拟生产者生产数据（根据实际需求，比如分页从数据库取数据）
    public void produceExportDataForTjcx(ExportDataAdapter<FeedbackExportVo> exportDataAdapter, CountDownLatch latch,
        Map<String, Object> queryParams){
        // 获取数据
        List<FeedbackExportVo> bjxxList = feedbackService.getFeedbackByParams(queryParams);

        if (!CollectionUtils.isEmpty(bjxxList)) {
            for (FeedbackExportVo FeedbackExportVo : bjxxList) {
                
            	if(FeedbackExportVo.getStatus() != null && !("").equals(FeedbackExportVo.getStatus())) {
	                String status = "";
	                if (FeedbackExportVo.getStatus().equals("0")) {
	                	status = "未处理";
	                }else if(FeedbackExportVo.getStatus().equals("1")) {
	                	status = "已处理";
	                }
	                FeedbackExportVo.setStatus(status);
            	}
                
            	if(FeedbackExportVo.getWtStatus() != null && !("").equals(FeedbackExportVo.getWtStatus())) {
	                String wtStatus = "";
	                if (FeedbackExportVo.getWtStatus().equals("1")) {
	                	wtStatus = "无法报警";
	                }else if(FeedbackExportVo.getWtStatus().equals("2")) {
	                	wtStatus = "查询有误";
	                }else if(FeedbackExportVo.getWtStatus().equals("3")) {
	                	wtStatus = "设备异常";
	                }else if(FeedbackExportVo.getWtStatus().equals("4")) {
	                	wtStatus = "界面不美观";
	                }else {
	                	wtStatus = "其它";
	                }
	                FeedbackExportVo.setWtStatus(wtStatus);
            	}
            	//添加入队列
                exportDataAdapter.addData(FeedbackExportVo);
            }
        }

        System.out.println("数据生产完成");
        //数据生产结束
        latch.countDown();
    }
}
